package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 购物车商品列表
        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();

        // 订单商品id列表
        List<Long> productIds = createOrderContext.getBuyProductIds();

        // 如果订单商品id列表为空，则获取购物车商品id列表
        if (CollectionUtils.isEmpty(productIds)) {
            productIds = dtoList.stream().map(CartProductDto::getProductId).collect(Collectors.toList());
        }

        // 根据id大小进行排序
        productIds.sort(Long::compareTo);

        // 为了不出错，库存表中没有该商品就会新建一个
        for (Long productId : productIds) {

            Stock stock1 = stockMapper.selectByPrimaryKey(productId);
            if (stock1 == null) {
                Stock stock = new Stock();
                stock.setItemId(productId);
                stock.setStockCount((long) 1000);
                stockMapper.insertSelective(stock);
            }
        }

        // 锁定订单商品的库存
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(productIds);

        // 如果商品的库存没有初始化，抛出异常
        if (CollectionUtils.isEmpty(stocksForUpdate)) {
            throw new BizException("库存未初始化！");
        }

        // 如果只有部分商品未初始化
        if (productIds.size() != stocksForUpdate.size()) {
            throw new BizException("部分商品未初始化！");
        }

        // 扣减商品库存
        for (CartProductDto cartProductDto : dtoList) {

            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            // TODO：productNum不能超过限购数量

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);

            stockMapper.updateStock(stock);
        }

        return true;
    }
}